package myATMCaseV1;

import jdbcUtils.JdbcUtilsV5;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import java.sql.Connection;
import java.sql.SQLException;

//账户数据层
public class AccountData {
    QueryRunner queryRunner = new QueryRunner();

    /**
     * 登陆账户并查询账户信息（通过账号uid和密码password）
     * @param uid 账号
     * @param password 密码
     * @return 返回该用户的Account对象，里面包含账户的所有信息
     */
    public Account accountLogin(Integer uid, String password){
        String sql = "SELECT * FROM account WHERE uid=? AND password=?";
        Connection connection = JdbcUtilsV5.getThreadConnection();
        Account account = null;
        try {
            account = queryRunner.query(connection, sql, new BeanHandler<Account>(Account.class), uid,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return account;
    }

    /**
     * 修改账户数据
     * @param account 传入的account对象（已经在业务层进行了数据修改的）
     * @return 返回值：1表示数据库修改数据成功；-1表示数据库修改数据失败
     */
    public int accountUpdate(Account account){
        String sql = "UPDATE account SET username=?,password=?,balance=? WHERE uid=?";
        Connection connection = JdbcUtilsV5.getThreadConnection();
        int resultNum = -1;
        try {
            resultNum = queryRunner.update(connection, sql, account.getUsername(), account.getPassword(), account.getBalance(), account.getUid());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return resultNum;
    }

    /**
     * 查询账户信息（通过uid）
     * @param uid 用户输入的uid
     * @return 返回该uid的account对象，如果没有找到，则返回null
     */
    public Account accountQuery(Integer uid){
        String sql = "SELECT * FROM account WHERE uid=?";
        Connection connection = JdbcUtilsV5.getThreadConnection();
        Account account = null;
        try {
            account = queryRunner.query(connection, sql, new BeanHandler<Account>(Account.class), uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return account;
    }

}
